/*
 * @Author: wangjh wangjiahui0710@163.com
 * @Date: 2024-07-23 09:35:21
 * @LastEditors: wangjh wangjiahui0710@163.com
 * @LastEditTime: 2024-09-11 11:40:53
 * @FilePath: \fbhgl_client\src\routers\index.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import "./types";

import type { App } from "vue";
import { createRouter, createWebHashHistory } from "vue-router/auto";

import { useUserStore } from "@/stores/user";
import { routes } from "vue-router/auto-routes";

const genRoutes = () => {
	return [
		routes.find((e) => e.path === "/login")!,
		{
			path: "/",
			name: "BasicLayout",
			component: () => import("@/layouts").then((e) => e.BasicLayout),
			children: routes.filter((item) => item.path !== "/login"),
		},
		// 404自动跳转到主页
		{
			path: "/:pathMatch(.*)*",
			redirect: "/",
		},
	];
};

/**
 *
 * 根据路径自动生成定制化路由
 * unplugin-vue-router
 * https://github.com/posva/unplugin-vue-router
 * https://uvr.esm.is/
 */

export const router = createRouter({
	history: createWebHashHistory("/base"),
	routes: genRoutes(),
});

router.beforeEach(async (to, _from, next) => {
	const userStore = useUserStore();

	if (to.name !== "LoginPage" && !userStore.isLogined) {
		return next({ name: "LoginPage" });
	}
	try {
		if (userStore.isLogined && !userStore.userInfo?.userId) {
			await userStore.getUserInfo();
		}
	} catch (error) {
		console.error(error);
	}
	if (
		to.matched.filter((e) => e.path === "/park").length &&
		userStore.userType !== "admin"
	) {
		return next({ path: "/" });
	}
	if (
		to.path === "/" &&
		["admin", "enterprise"].includes(userStore.userType!)
	) {
		return next({
			path:
				userStore.userType === "enterprise"
					? "/company/home-page"
					: "/park/home-page",
		});
	}

	return next();
});

export function setupRouter(app: App) {
	return app.use(router);
}
